//
//  SetAndHelpViewController.m
//  1gene
//
//  Created by 1jiyin on 16/3/24.
//  Copyright © 2016年 1jiyin. All rights reserved.
//
//********设置与帮助********
#import "SetAndHelpViewController.h"
#import <RongIMKit/RongIMKit.h>
#import "SoftworeExplainViewController.h"
#import "DataBaseMananger.h"

#define kCurrentUserToken [[NSUserDefaults standardUserDefaults]objectForKey:@"token"]

@interface SetAndHelpViewController ()<UIAlertViewDelegate>

@end

@implementation SetAndHelpViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:[UIView new]];
    [self createNavigation];
    [self createUI];
    // Do any additional setup after loading the view.
}

-(void)createUI
{
    //清除缓存
    UILabel *l1=[[UILabel alloc]initWithFrame:CGRectMake(30, 20+44, 100, 50)];
    l1.text=@"清除缓存";
    l1.font=[UIFont systemFontOfSize:15];
    l1.textColor=[UIColor blackColor];
    [self.view addSubview:l1];
    
    UIImageView *imgView1=[[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width-30-15, l1.frame.origin.y+(50-20)/2.0, 20, 20)];
    imgView1.image=[UIImage imageNamed:@"app_right"];
    [self.view addSubview:imgView1];
    UIButton *b1=[UIButton buttonWithType:UIButtonTypeCustom];
    b1.tag=1;
    b1.frame=CGRectMake(0, l1.frame.origin.y, self.view.frame.size.width, l1.frame.size.height);
    [b1 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:b1];
    
    //划线
    UIView *line1=[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(b1.frame), self.view.frame.size.width, 0.5)];
    line1.backgroundColor=[UIColor colorWithRed:235/255.0 green:235/255.0 blue:241/255.0 alpha:1];
    [self.view addSubview:line1];
    
    //检查更新
    UILabel *l2=[[UILabel alloc]initWithFrame:CGRectMake(30, CGRectGetMaxY(line1.frame), 100, 50)];
    l2.text=@"检查更新";
    l2.font=[UIFont systemFontOfSize:15];
    l2.textColor=[UIColor blackColor];
    [self.view addSubview:l2];
    
    //当前版本
    UILabel *currentVersion=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(l2.frame)+10, l2.frame.origin.y, self.view.frame.size.width-CGRectGetMaxX(l2.frame)-20-15-10-10, 50)];
    currentVersion.text=@"当前版本:1.0";
    currentVersion.font=[UIFont systemFontOfSize:12];
    currentVersion.textColor=[UIColor blackColor];
    currentVersion.textAlignment=NSTextAlignmentRight;
    [self.view addSubview:currentVersion];
    
    UIImageView *imgView2=[[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width-30-15, l2.frame.origin.y+(50-20)/2.0, 20, 20)];
    imgView2.image=[UIImage imageNamed:@"app_right"];
    [self.view addSubview:imgView2];
    UIButton *b2=[UIButton buttonWithType:UIButtonTypeCustom];
    b2.tag=2;
    b2.frame=CGRectMake(0, l2.frame.origin.y, self.view.frame.size.width, l2.frame.size.height);
    [b2 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:b2];
    
    //划线
    UIView *line2=[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(b2.frame), self.view.frame.size.width, 0.5)];
    line2.backgroundColor=[UIColor colorWithRed:235/255.0 green:235/255.0 blue:241/255.0 alpha:1];
    [self.view addSubview:line2];
    
    //免责声明
    UILabel *l3=[[UILabel alloc]initWithFrame:CGRectMake(30, CGRectGetMaxY(line2.frame), 100, 50)];
    l3.text=@"免责声明";
    l3.font=[UIFont systemFontOfSize:15];
    l3.textColor=[UIColor blackColor];
    [self.view addSubview:l3];
    
    UIImageView *imgView3=[[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width-30-15, l3.frame.origin.y+(50-20)/2.0, 20, 20)];
    imgView3.image=[UIImage imageNamed:@"app_right"];
    [self.view addSubview:imgView3];
    UIButton *b3=[UIButton buttonWithType:UIButtonTypeCustom];
    b3.tag=3;
    b3.frame=CGRectMake(0, l3.frame.origin.y, self.view.frame.size.width, l3.frame.size.height);
    [b3 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:b3];
    //划线
    UIView *line3=[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(b3.frame), self.view.frame.size.width, 0.5)];
    line3.backgroundColor=[UIColor colorWithRed:235/255.0 green:235/255.0 blue:241/255.0 alpha:1];
    [self.view addSubview:line3];
    
    
    //设置健康档案密码
    UILabel *l4=[[UILabel alloc]initWithFrame:CGRectMake(30, CGRectGetMaxY(line3.frame), 150, 50)];
    l4.text=@"设置健康档案密码";
    l4.font=[UIFont systemFontOfSize:15];
    l4.textColor=[UIColor blackColor];
    [self.view addSubview:l4];
    
    UIImageView *imgView4=[[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width-30-15, l4.frame.origin.y+(50-20)/2.0, 20, 20)];
    imgView4.image=[UIImage imageNamed:@"app_right"];
    [self.view addSubview:imgView4];
    UIButton *b4=[UIButton buttonWithType:UIButtonTypeCustom];
    b4.tag=4;
    b4.frame=CGRectMake(0, l4.frame.origin.y, self.view.frame.size.width, l4.frame.size.height);
    [b4 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:b4];
    //划线
    UIView *line4=[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(b4.frame), self.view.frame.size.width, 0.5)];
    line4.backgroundColor=[UIColor colorWithRed:235/255.0 green:235/255.0 blue:241/255.0 alpha:1];
    [self.view addSubview:line4];
    
    //修改健康档案密码
    UILabel *l5=[[UILabel alloc]initWithFrame:CGRectMake(30, CGRectGetMaxY(line4.frame), 150, 50)];
    l5.text=@"修改健康档案密码";
    l5.font=[UIFont systemFontOfSize:15];
    l5.textColor=[UIColor blackColor];
    [self.view addSubview:l5];
    
    UIImageView *imgView5=[[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width-30-15, l5.frame.origin.y+(50-20)/2.0, 20, 20)];
    imgView5.image=[UIImage imageNamed:@"app_right"];
    [self.view addSubview:imgView5];
    
    UIButton *b5=[UIButton buttonWithType:UIButtonTypeCustom];
    b5.tag=5;
    b5.frame=CGRectMake(0, l5.frame.origin.y, self.view.frame.size.width, l5.frame.size.height);
    [b5 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:b5];
    
    //划线
    UIView *line5=[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(b5.frame), self.view.frame.size.width, 0.5)];
    line5.backgroundColor=[UIColor colorWithRed:235/255.0 green:235/255.0 blue:241/255.0 alpha:1];
    [self.view addSubview:line5];

    //取消健康档案密码
    UILabel *l6=[[UILabel alloc]initWithFrame:CGRectMake(30, CGRectGetMaxY(line5.frame), 150, 50)];
    l6.text=@"取消健康档案密码";
    l6.font=[UIFont systemFontOfSize:15];
    l6.textColor=[UIColor blackColor];
    [self.view addSubview:l6];
    
    UIImageView *imgView6=[[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width-30-15, l6.frame.origin.y+(50-20)/2.0, 20, 20)];
    imgView6.image=[UIImage imageNamed:@"app_right"];
    [self.view addSubview:imgView6];
    
    UIButton *b6=[UIButton buttonWithType:UIButtonTypeCustom];
    b6.tag=6;
    b6.frame=CGRectMake(0, l6.frame.origin.y, self.view.frame.size.width, l6.frame.size.height);
    [b6 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:b6];
    
    //划线
    UIView *line6=[[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(b6.frame), self.view.frame.size.width, 0.5)];
    line6.backgroundColor=[UIColor colorWithRed:235/255.0 green:235/255.0 blue:241/255.0 alpha:1];
    [self.view addSubview:line6];
    
#warning 张国文写的判断用户是否登陆
    
    NSLog(@"用户token长度%ld，token = %@",[NSString stringWithFormat:@"%@", kCurrentUserToken].length, kCurrentUserToken);
    //退出登录
    UIButton *changeBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    changeBtn.frame=CGRectMake((self.view.frame.size.width-150)/2.0, CGRectGetMaxY(line6.frame)+30, 150, 35);
    // 判断用户是否登录
    if ([NSString stringWithFormat:@"%@", kCurrentUserToken].length == 6 || [kCurrentUserToken isEqualToString:@"(null)"]) {
      // 说明没登录
        [changeBtn setTitle:@"马上登录" forState:UIControlStateNormal];
    } else {
        // 说明登陆
        [changeBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    }
    [changeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    changeBtn.titleLabel.font=[UIFont systemFontOfSize:20];
    changeBtn.backgroundColor=[UIColor colorWithRed:84/255.0 green:199/255.0 blue:222/255.0 alpha:1];
    changeBtn.layer.borderColor=[UIColor colorWithRed:84/255.0 green:199/255.0 blue:222/255.0 alpha:1].CGColor;
    changeBtn.layer.borderWidth=2.0;
    changeBtn.layer.cornerRadius=5.0;
    [changeBtn addTarget:self action:@selector(changeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:changeBtn];
}
//
-(void)btnClick:(UIButton *)sender
{
    if (sender.tag==1) {
        //清除缓存
        [self showClearAlertView];
    }else if (sender.tag==2){
        //检查更新
        [self showCurrentVersionAlertView];
    }else if (sender.tag==3){
        //免责声明
        SoftworeExplainViewController *vc=[SoftworeExplainViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }else if (sender.tag==4){
        //设置健康档案密码
        SetHealthPasswordViewController *vc=[[SetHealthPasswordViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if (sender.tag==5){
        NSLog(@"修改健康档案密码");
        //修改健康档案密码
        ChangeHealthPasswordViewController *vc=[[ChangeHealthPasswordViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if (sender.tag==6){
        NSLog(@"取消健康档案密码");
        //取消健康档案密码
        [self cancelHealthPassword];
    }
}




-(void)showClearAlertView
{
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"壹基因" message:@"确定清楚缓存吗" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}
//退出登录
-(void)changeBtnClick:(UIButton *)sender
{
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *str=[user objectForKey:@"tiaoguo"];
    if ([str isEqualToString:@"tiaoguo"]) {
        AppDelegate *app=[UIApplication sharedApplication].delegate;
        [user setObject:nil forKey:@"tiaoguo"];
        [user synchronize];
        [app showMainViewController:0];
    }else{
        [self getLogOutHttpData];
    }
    
    
}
-(void)createNavigation
{
    self.navigationController.navigationBar.barTintColor=[UIColor colorWithRed:84/255.0 green:199/255.0 blue:222/255.0 alpha:1];
    //返回
    UIButton *leftBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame=CGRectMake(0, 0, 25, 25);
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"left_back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(leftBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    
    //标题
    UILabel *title=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 44)];
    title.text=@"设置与帮助";
    title.font=[UIFont systemFontOfSize:22];
    title.textAlignment=NSTextAlignmentCenter;
    title.textColor=[UIColor whiteColor];
    self.navigationItem.titleView=title;
    
    //忘记密码
    UIButton *rightBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame=CGRectMake(0, 0, 60, 30);
    [rightBtn setTitle:@"忘记密码" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor  whiteColor] forState:UIControlStateNormal];
    rightBtn.titleLabel.font=[UIFont systemFontOfSize:12];
    [rightBtn addTarget:self action:@selector(rightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:rightBtn];
}
//忘记密码
-(void)rightBtnClick:(UIButton *)sender
{
    
    ForgotPasswordViewController *vc=[ForgotPasswordViewController new];
    //SelectedPasswordTypeViewController *vc=[[SelectedPasswordTypeViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
    
    
    
}
//返回上一页
-(void)leftBtnClick:(UIButton *)sender
{
    self.navigationController.navigationBar.hidden=YES;
    self.tabBarController.tabBar.hidden=NO;
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)showCurrentVersionAlertView
{
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:nil message:@"已经是最新版本" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //NSLog(@"=====%ld",buttonIndex);
    if (buttonIndex==1) {
        [self myClearCacheAction];
    }
}
#pragma mark === 暂时不用清除缓存=====
-(void)myClearCacheAction{
#warning 张国文修改逻辑，因为发现图片清理缓存清理不了，要写在外面，并且添加清理聊天数据
    // 清理图片缓存
    [[SDImageCache sharedImageCache] clearDisk];
        dispatch_async(
                       dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                       , ^{
                           NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
                           NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
                           NSLog(@"files :%lu",(unsigned long)[files count]);
                           for (NSString *p in files) {
                               NSError *error;
                               NSString *path = [cachPath stringByAppendingPathComponent:p];
                               if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                                   NSLog(@"开始清理缓存");
                                   [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                               }
                           }
                           
                           // 清理本地数据库里面保存的本地对话
                           NSArray *benDiArray = [[DataBaseMananger shareManeger] getDataFromDB];
                         //  NSLog(@"清理之前：%@", [[DataBaseMananger shareManeger] getDataFromDB]);
                           for (int i = 0; i < benDiArray.count; i++) {
                               YTKKeyValueItem *item = benDiArray[i];
                               [[DataBaseMananger shareManeger] deleteDataWithID:item.itemId];
                           }
                        //   NSLog(@"清理过后：%@", [[DataBaseMananger shareManeger] getDataFromDB]);
                           [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];});
}
-(void)clearCacheSuccess
{
    NSLog(@"清理成功");
    [self showClearCacheActionAlertView];
}
-(void)showClearCacheActionAlertView
{
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:nil message:@"清理成功" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
}

-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden=NO;
    self.tabBarController.tabBar.hidden=YES;
    self.navigationController.navigationBar.barStyle=UIBarStyleBlack;
    
   // [self.navigationController.navigationBar setTranslucent:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//退出登录
-(void)getLogOutHttpData
{
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    [self.view isLoading:YES];
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *token= [user objectForKey:@"token"];
    NSLog(@"token=======%@",token);
    [manager GET:[NSString stringWithFormat:@"%@%@",LogOut,token] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"login=======%@",dic);
        if (dic) {
            NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
            [user setObject:nil forKey:@"token"];
            [user setObject:nil forKey:@"userId"];
            [user setObject:nil forKey:@"userName"];
            [user setObject:nil forKey:@"userPhone"];
            [user setObject:nil forKey:@"userPassword"];
            [user setObject:nil forKey:@"rong_token"];
            [user synchronize];
            [[RCIM sharedRCIM]logout];
             [[NetStatusHandle shareHandle] saveLoginRCloudIsSuccess:@"NO"];

            dispatch_async(dispatch_get_main_queue(), ^{
                AppDelegate *app=[UIApplication sharedApplication].delegate;
                [app showMainViewController:0];
            });
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.view isLoading:NO];
        //[self.view showTiShiMessage:@"退出失败"];
        NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
        [user setObject:nil forKey:@"token"];
        [user setObject:nil forKey:@"userId"];
        [user setObject:nil forKey:@"userName"];
        [user setObject:nil forKey:@"userPhone"];
        [user setObject:nil forKey:@"userPassword"];
        [user setObject:nil forKey:@"rong_token"];
        [user synchronize];
        [[RCIM sharedRCIM]logout];
#warning 张国文的修改，用户保存融云的登陆状态
         [[NetStatusHandle shareHandle] saveLoginRCloudIsSuccess:@"NO"];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            AppDelegate *app=[UIApplication sharedApplication].delegate;
            [app showMainViewController:0];
        });

        NSLog(@"error====%@",error.localizedDescription);
    }];
}


//取消健康档案密码
-(void)cancelHealthPassword
{
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *token=[user objectForKey:@"token"];
    
    NSDictionary *params=@{@"privacy_pwd":@"000000",@"newprivacy_pwd":@"123456",@"newprivacy_pwd_comfired":@"123456"};
    
    [self.view isLoading:YES];
    [manager DELETE:[NSString stringWithFormat:CancelHealthPassword,token] parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.view isLoading:NO];
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"取消健康档案密码%@",dic);
            NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
            [user setBool:NO forKey:@"sethealthPassword"];
            [user setObject:nil forKey:@"healthPassword"];
            [user synchronize];
            [self.view showTiShiMessage:@"取消成功"];
        NSLog(@"=====%@",dic);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.view isLoading:NO];
        NSLog(@"error%@",error);
        [self.view showTiShiMessage:@"取消失败"];
    }];

}


//-(void)viewWillDisappear:(BOOL)animated
//{
//    [self.navigationController.navigationBar setTranslucent:NO];
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
